import { Application } from 'egg';
import { Browse } from '../model/Browse';
import * as moment from 'moment';

export default (app: Application) => {
    return {
        schedule: {
            interval: app.config.overTime,
            type: 'all',
            immediate: true,
        },
        async task() {
            const resultBrowse: any = await app.model.Browse.findAll<Browse>({
                attributes: ['browse_id', 'user_id', 'browse_timestamp', 'created_at'],
                where: { browse_status: '1', is_delete: '1' }
            });
            for (let i = 0; i < resultBrowse.length; i++) {
                const date=new Date();
                const dateStr=date.toLocaleString();
                const browse_timestamp = moment(resultBrowse[i].browse_timestamp).format('YYYY-MM-DD HH:mm:ss');
                const created_at = moment(resultBrowse[i].created_at).format('YYYY-MM-DD HH:mm:ss');;
                const stime = new Date(browse_timestamp).getTime();
                const etime = new Date(dateStr).getTime();
                const usedTime = etime - stime;  //两个时间戳相差的毫秒数	
                let minutes = usedTime / 60000;
                minutes = Number(minutes.toString().split('.')[0]);
                if (minutes > 5) {
                    const stime = new Date(created_at).getTime();
                    const etime = new Date(browse_timestamp).getTime();
                    const usedTime = etime - stime;  //两个时间戳相差的毫秒数	
                    let browse_time = usedTime / 60000;
                    browse_time = Number(browse_time.toString().split('.')[0]);
                    await app.model.Browse.update({ browse_time, browse_status: '2' }, { where: { browse_id: resultBrowse[i].browse_id } });
                    const user_id = resultBrowse[i].user_id;
                    await app.model.User.update({ is_online: '2', is_news: '2' }, { where: { user_id } });
                }
            }
        },
    };
};
